<template>
  <div>
    <el-dialog
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      title="选择优惠券"
      width="1120px"
      top="10vh"
      append-to-body
      @close="close"
    >
      <el-tag>
        <i class="el-icon-warning" />
        &nbsp;在此选择已经创建的{{ filterForm.source === 1 ? "普通券" : "活动券" }}
      </el-tag>
      <!-- 搜索 -->
      <div class="flexRBC">
        <div class="list-search">
          <el-input
            v-model="filterForm.couponName"
            placeholder="请输入券名称"
            @keyup.enter.native="searchByKeyword"
          />
          <el-button
            :loading="searchLoading"
            type="primary"
            size="medium"
            round
            icon="el-icon-search"
            @click="searchByKeyword"
          >查 询
          </el-button>
        </div>
        <div>
          <el-button round size="medium" @click="refresh">刷 新</el-button>
          <!--<el-button round size="medium" @click="goCouponAdd('add')">新建券</el-button>-->
        </div>
      </div>

      <div class="content">
        <!-- 列表 -->
        <el-table
          v-loading="tableLoading"
          :data="list"
          border
          stripe
          style="width: 100%"
          size="small"
          element-loading-text="加载中"
          empty-text="暂无数据"
        >
          <el-table-column prop="couponName" label="券名称" fixed />
          <el-table-column prop="identityCode" label="券id" fixed width="160" />
          <el-table-column prop="createTime" label="创建时间" width="150" />
          <el-table-column prop="couponType" label="类型" width="100">
            <template slot-scope="scope">
              <span>{{ couponTypeTableOptions[scope.row.couponType] }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述" />
          <el-table-column prop="dateType" label="有效期" width="200">
            <template slot-scope="scope">
              <div v-if="scope.row.dateType==='DATE_TYPE_FIX_TERM'">
                <span>生效后{{ scope.row.fixedTerm }}天内有效,</span>
                <span v-if="scope.row.fixedBeginTerm===0">立即生效</span>
                <span v-else>第二天生效</span>
              </div>
              <div v-if="scope.row.dateType==='DATE_TYPE_FIX _TIME_RANGE'">
                <div>开始：{{ scope.row.beginTime }}</div>
                <div>结束：{{ scope.row.endTime }}</div>
              </div>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="quantity"  label="剩余库存">
            <template slot-scope="scope">
              <span>{{scope.row.quantity===-1?"不限":parseNumberToThousands(scope.row.quantity,0,false)}}</span>
            </template>
          </el-table-column>-->
          <el-table-column label="操作" width="100" fixed="right">
            <template slot-scope="scope">
              <el-button v-if="scope.row.quantity===0" type="text" size="small" disabled>无库存</el-button>
              <el-button
                v-if="scope.row.quantity!==0"
                :disabled="couponCheckedIds.includes(scope.row.id)"
                type="text"
                size="small"
                @click="choose(scope.row)"
              >{{ couponCheckedIds.includes(scope.row.id) ? '已选' : '选择' }}
              </el-button>
              <el-button
                v-if="scope.row.quantity!==0"
                type="text"
                size="small"
                @click="openCouponDetail(scope.row)"
              >详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <pagination-direction
          v-if="paginationConfig.total!==0"
          :config="paginationConfig"
          @sizeschange="sizesChange"
          @pagechange="pageChange"
        />
      </div>
    </el-dialog>

    <!-- 券详情 -->
  </div>
</template>

<script>
// import bus from "@/utils/bus";

export default {
  components: {
  },
  data() {
    return {
      // 配置
      // 分页配置
      paginationConfig: {
        direction: 'center', // 分页位置
        layout: 'total, prev, pager, next, jumper', // 分页类型
        pageSizes: [10, 20], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10 // 每页条数-默认10
      },
      couponTypeOptions: [
        { label: 'CASH', value: '代金券' },
        { label: 'DISCOUNT', value: '折扣券' },
        { label: 'GENERAL', value: '通用券' }
      ],
      couponTypeTableOptions: {
        GENERAL: '通用券',
        CASH: '代金券',
        DISCOUNT: '折扣券'
      },
      resolve: null,
      reject: null,
      // 状态
      dialogVisible: null,
      tableLoading: false, // 表格loading
      searchLoading: false, // 搜索loadings
      // 数据
      list: [], // 表格数据
      couponCheckedIds: [],
      // 筛选数据
      filterForm: {
        couponName: '',
        status: 1,
        couponType: 'all',
        source: ''
      },
      filterType: 'key'
    }
  },
  methods: {
    open(ids, source = '') {
      this.filterForm.source = source
      this.couponCheckedIds = ids
      this.initData()
      this.show()
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    show() {
      this.dialogVisible = true
    },

    close() {
      this.filterForm = {
        couponName: '',
        couponType: 'all',
        source: '',
        status: 1
      }
      this.list = []
      this.couponCheckedIds = []
    },

    hide() {
      this.resolve = null
      this.reject = null
      this.dialogVisible = false
    },

    /**
     * 获取数据
     */
    // 获取数据
    initData(
      page = this.paginationConfig.page,
      pageSize = this.paginationConfig.pageSize
    ) {
      // 加入page
      this.filterForm.page = page
      this.filterForm.pageSize = pageSize
      const params = Object.assign({}, this.filterForm)
      // 如果是key搜索
      if (this.filterType === 'key') {
        // 不携带筛选数据
        delete params.couponType
      }
      // 清除多余字段
      for (const key in params) {
        if (params[key] === '' || params[key] === 'all') {
          delete params[key]
        }
      }
      this.tableLoading = false
      this.searchLoading = false
    },

    // 分页sizes改变
    sizesChange() {
      this.initData()
    },

    // 分页page改变
    pageChange() {
      this.initData()
    },

    /**
     * 按钮组
     */

    // 打开详情
    openCouponDetail(row) {
      this.$refs.couponDetail.open(row.id)
    },

    // 搜索
    searchByKeyword() {
      this.searchLoading = true
      this.filterType = 'key'
      this.initData(1)
    },

    // 刷新
    refresh() {
      this.filterForm.couponName = ''
      this.initData(1)
    },

    // 新增
    goCouponAdd(type) {
      if (this.filterForm.source === 1) {
        const routeUrl = this.$router.resolve({
          name: 'CouponEditForGeneral',
          query: { callback: true }
        })
        window.open(routeUrl.href, '_blank')
      } else {
        const routeUrl = this.$router.resolve({
          name: 'CouponEditForActivity',
          query: { callback: true }
        })
        window.open(routeUrl.href, '_blank')
      }
    },

    // 选择
    choose(row) {
      const params = {
        couponId: row.id,
        couponName: row.couponName,
        couponType: row.couponType,
        denomination: null,
        amount: 1,
        description: row.description,
        identityCode: row.identityCode
      }
      switch (params.couponType) {
        case 'CASH':
          params.denomination = row.reduceCost
          break
        case 'DISCOUNT':
          params.denomination = row.discount
          break
        // case 'GENERAL':
        //   params.denomination = row.description
        //   break
      }
      this.resolve && this.resolve(params)
      this.hide()
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
/* 搜索*/
.list-search {
  margin-top: 10px;

  .el-input {
    width: 300px;
    // min-width: 200px;
    // max-width: 700px;
    margin-right: 10px;
  }
}

.content {
  margin-top: 10px;
}
</style>
